app.controller('eventController', ['$scope', 'storageService', '$routeParams',
    function ($scope, storageService, $routeParams) {
        var id = $routeParams['id'];
        var path = 'events';
        $scope.event = storageService.getById(path, id);
        
        // Check for updates and update data when done
        storageService.dataUpdated(path).then(function(results){
            if(results.data !== localStorage.getItem(path + '_updated')){
                storageService.updateData(path).then(function(){
                    $scope.event = storageService.getById(path, id);
                });
            } 
        });
        
        $scope.setFav = function(){
            if($scope.isFav){
                // The event was a fav, remove it
                $scope.isFav = false;
                removeFav();
            } else {
                // The event is not a fav, add it
                $scope.isFav = true;
                addFav();
            }
        };
        
        checkFavs();
        
        // Favorite stuff - which button to display
        function checkFavs(){
            if(localStorage.getItem('favs')){
                var favs = localStorage.getItem('favs').split(',');
                for(var i = 0; i < favs.length; i++){
                    if(favs[i] === id){
                        $scope.isFav = true;
                    }
                }
            } else {
                $scope.isFav = false;
            }        
        };
        
        function removeFav(){
            var favs = localStorage.getItem('favs').split(',');
            
            if(favs.length === 1){
                localStorage.removeItem('favs');
            } else {
                // Loop through the array to find the right id
                for(var i = 0; i < favs.length; i++){
                    if(favs[i] === id){
                        favs.splice(i, 1);
                        localStorage.setItem('favs', favs.toString());
                    }
                }
            }
            
        };
        
        function addFav(){
            // The event is not a fav, add it
            $scope.isFav = true;
            // check if there are already favories
            if(localStorage.getItem('favs')){
                var favs = localStorage.getItem('favs').split(',');
                favs.push(id);
                localStorage.setItem('favs', favs.toString());
            } else {
                // There were no prior favs
                var favs = [ id ];
                localStorage.setItem('favs', favs.toString());
            }
        };
        
        
        
}]);